import { PLATFORM_NAME } from '../plugins/constant'
import store from '../store'

const logoutToLogin = (next, path) => {
  store.dispatch('logout').finally(() => {
    next({ path: '/login', query: { redirect: path } })
  })
}

export default {
  // 设置页面的title
  setTitle(to, from, next) {
    if (to.meta.title) {
      document.title = `${to.meta.title} - ${PLATFORM_NAME}`
    }
    next()
  },

  // 权限验证
  authLogin(to, from, next) {
    if (store.getters.user.userId || (to.meta && to.meta.whiteList) || to.path === '/login') {
      return next()
    }

    Promise.all([store.dispatch('getMe'), store.dispatch('getOrg')])
      .then(([user, org]) => {
        // 根据用户信息生成可访问的路由表
        store.dispatch('generateRoutes', user)
        store.dispatch('setPermissions', { user, org })
      })
      .then(() => {
        // 确保addRoutes已完成
        next({ ...to, replace: true })
      })
      .catch(err => {
        // 当获取用户信息失败时，前端登出，不调用接口登出
        logoutToLogin(next, to.fullPath)
        throw err
      })
  },
}
